package web.blogsphere.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import web.blogsphere.model.CaptchaProperty;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private final static long session_valid_timeout = 60 * 1000;

    @Autowired
    private CaptchaProperty captchaProperty;

    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse httpServletResponse, HttpSession session){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperty.getWidth(), captchaProperty.getHeight());

//        设置返回类型
        httpServletResponse.setContentType("image/jpeg");

//        禁止缓存
        httpServletResponse.setHeader("Progma", "No-cache");

        //图形验证码写出，可以写出到文件，也可以写出到流
        try {
            lineCaptcha.write(httpServletResponse.getOutputStream());
            session.setAttribute(captchaProperty.getSession().getKey(),lineCaptcha.getCode());
            session.setAttribute(captchaProperty.getSession().getDate(), new Date());
            httpServletResponse.getOutputStream().close();//关闭流
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("check")
    public Boolean check(String code,HttpSession session){
//        用户输入的 与生成的进行对比
        if (!StringUtils.hasLength(code)){
            return false;
        }
//        从 session 中 获取用户输入的内容
        String captchaCode = (String) session.getAttribute(captchaProperty.getSession().getKey());
        Date captchaDate = (Date) session.getAttribute(captchaProperty.getSession().getDate());
        if (code.equalsIgnoreCase(captchaCode)){
//            忽略大小写
//            判断验证码是否过期
            if (captchaDate == null || System.currentTimeMillis() - captchaDate.getTime() > session_valid_timeout){
                return false;
            }
            return true;
        }
        return false;
    }
}
